var mysql = require('mysql');
var path = require('path');
var fs = require('fs');
var config = require('./config');

var pool = mysql.createPool({
    connectionLimit: config.database.connectionLimit,
    host: config.database.host,
    port: config.database.port,
    user: config.database.user,
    password: config.database.password,
    database: config.database.database
});

//  MySQL8: 客户端连接caching-sha2-password问题
//      修改加密规则: ALTER USER 'root'@'localhost' IDENTIFIED BY 'password' PASSWORD EXPIRE NEVER;
//      更新一下用户的密码: ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';
//      刷新权限: FLUSH PRIVILEGES;
//      再重置下密码: alter user 'root'@'localhost' identified by 'alex007';

function setup() {
    console.log("开始创建数据表...");
    var tablePath = path.resolve('resources/tables.sql');
    var data = fs.readFileSync(tablePath, 'utf8');
    var splited = data.split('\n\n');
    splited.forEach(function(item, index) {
        if (item.length > 0) {
            pool.query(item, function (err, results, fileds) {
                if (err) {
                    console.log("数据表创建出错: " + err);
                } else {
                    console.log(index+"数据表创建完成!");
                }
            });
        }
    });
}

function query(sql, options, callback) {
    pool.query(sql, options, callback);
}

module.exports.setup = setup;
module.exports.query = query;